<template>
  <div class="container">
    <div ref="leftMainRef" class="left-main" :style="{width:currentIndex === 2?'500px':'395px'}">
      <div ref="tableRef" class="table">
        <div ref="titleRef" class="title-container">
          <div :class="{ currentTable: currentIndex === 1 }" class="title-name" @click="changeCurrent(1)">站点模式</div>
          <div :class="{ currentTable: currentIndex === 2 }" class="title-name" @click="changeCurrent(2)">配送员模式</div>
        </div>
        <div class="table-container">
          <keep-alive>
            <table-1 :is="currentTable" v-if="currentIndex === 1" ref="table1" :table-data="tableData2" @currentRow="currentRow" @currentChild="currentChild" />
            <table-2 :is="currentTable" v-if="currentIndex === 2" ref="table2" :choose-id="chooseOrgId" :table-data="tableData1" @chooseOrg="chooseOrg" @currentRow="currentRow" @add="add" />
          </keep-alive>
        </div>
      </div>
      <div class="toggleBtn">
        <i v-show="flag" class="el-icon-caret-left" @click="changeView(false)" />
        <i v-show="!flag" class="el-icon-caret-right" @click="changeView(true)" />
      </div>
    </div>
    <div ref="rightMainRef" class="right-main">
      <div class="name-box"><el-checkbox v-model="showName">显示名称</el-checkbox></div>
      <baidu-map
        class="bm-view"
        :center="center"
        :scroll-wheel-zoom="true"
        @ready="ready"
      >
        <bm-control anchor="BMAP_ANCHOR_TOP_LEFT">
          <bm-auto-complete v-model="keyword" :sug-style="{zIndex: 1}" :location="location">
            <div class="search-box">
              <el-input v-model.trim="keyword" placeholder="请输入地名关键字" />
            </div>
          </bm-auto-complete>
        </bm-control>
        <bm-local-search :keyword="keyword" :auto-viewport="true" :location="location" :force-local="true" />
        <bm-marker v-if="form.markShow" :position="{lng: form.longitude, lat: form.latitude}" :dragging="true" @dragend="dragend">
          <bm-label :content="form.fenceName" :label-style="{color: 'blue', fontSize : '12px', textAlign: 'center' , width: '80px', background: 'none' , border: 'none'}" :offset="{width:-20, height: -20}" />
        </bm-marker>
        <bm-control v-if="controlShow" anchor="BMAP_ANCHOR_TOP_RIGHT">
          <div class="toolbar">
            <div class="title">{{ currentItem.orgName }}</div>
            <el-form
              ref="dataForm"
              class="form"
              :rules="rules"
              :model="form"
              label-position="left"
              label-width="110px"
            >
              <el-form-item label="围栏名称:" prop="fenceName" label-width="90px">
                <el-input v-model.trim="form.fenceName" />
              </el-form-item>
              <el-form-item label="边界颜色:" prop="borderColor" label-width="90px">
                <!-- <el-input v-model.trim="form.borderColor" /> -->
                <colorPicker v-model="form.borderColor" @change="changeBorderColor" />
              </el-form-item>
              <el-form-item label="填充颜色:" prop="fillColor" label-width="90px">
                <!-- <el-input v-model.trim="form.fillColor" default-color="#4991E9"/> -->
                <colorPicker v-model="form.fillColor" @change="changeFillColor" />
              </el-form-item>
              <el-form-item label="填充透明度:" prop="fillOpacity">
                <el-slider v-model="form.fillOpacity" :step="0.1" :min="0.1" :max="0.9" @change="changeFillOpacity" />
              </el-form-item>
              <el-form-item label="地图选点:" label-width="90px">
                <img style="cursor: pointer;" src="@/assets/map_images/red_sprite.png" @click="chooseMark">
              </el-form-item>
              <el-form-item v-show="form.markShow" label="经度:" label-width="50px">
                <el-input v-model.trim="form.longitude" disabled />
              </el-form-item>
              <el-form-item v-show="form.markShow" label="纬度:" label-width="50px">
                <el-input v-model.trim="form.latitude" disabled />
              </el-form-item>
              <!-- <el-form-item label="围栏面积:" prop="fenceArea">
                <el-input v-model.trim="form.fenceArea" readonly />
              </el-form-item> -->
            </el-form>
            <!-- <div class="toolbar-item" />
            <div class="toolbar-item" />
            <div class="toolbar-item" />
            <div class="toolbar-item" /> -->
            <div class="toolbar-item">
              <!-- <el-button
                :disabled="drawBtn"
                @click="draw"
              >
                <i class="el-icon-crop" />&emsp;画区
              </el-button> -->
              <el-button
                :disabled="drawBtn"
                @click="draw"
              >
                <i class="el-icon-crop" />&emsp;画区
              </el-button>
              <el-button
                :disabled="editBtn"
                @click="editing"
              >
                <i class="el-icon-edit-outline" />&emsp;编辑
              </el-button>
              <el-button
                :disabled="resetBtn"
                @click="clearAll"
              >
                <i class="el-icon-copy-document" />&emsp;重置
              </el-button>
              <el-button
                :disabled="resetBtn"
                @click="success"
              >
                <i class="el-icon-circle-check" />&emsp;保存
              </el-button>
              <el-button
                :disabled="!currentItem"
                @click="cancelView"
              >
                <i class="el-icon-delete-solid" />&emsp;取消
              </el-button>
            </div>
          </div>
        </bm-control>
        <!-- <bm-polygon
          v-for="(item,index) in tableData"
          v-show="item.show"
          :key="index"
          :stroke-color="item.borderColor"
          :fill-color="item.fillColor"
          :stroke-opacity="0.5"
          :stroke-weight="2"
          :editing="false"
          :path="item.path"
          @ready="ready"
        /> -->
        <!-- <bm-polygon
          v-for="path of polygonPath.paths"
          :key="path.toString()"
          :path="path"
          stroke-color="blue"
          fill-color="red"
          :fill-opacity="0.8"
          :stroke-opacity="0.5"
          :stroke-weight="2"
          :editing="true"
          覆盖物可编辑
          为了监测编辑覆盖物事件
          @click="alertpath"
          @lineupdate="updatePolygonPath"
        /> -->
        <!-- <bm-marker v-for="item in tableData" :key="item.orgId" :position="item.position" :icon="markerIcon" :dragging="false" @mouseover="showInfo(item)">
          <bm-label :content="item.orgName" :labelStyle="{color: 'red', fontSize : '12px', textAlign: 'center' , width: '80px', background: 'none' , border: 'none'}" :offset="{width:-20, height: -20}"/>
          <bm-info-window :show="item.showDetail" >
          <el-descriptions :column="1" :v-model="item">
            <el-descriptions-item label="站点">{{ item.orgName }}</el-descriptions-item>
            <el-descriptions-item label="机构编码">{{ item.orgCode }}</el-descriptions-item>
            <el-descriptions-item label="是否为加盟店">{{ (item.orgOption>>2)&1?'是':'否' }}</el-descriptions-item>
            <el-descriptions-item label="负责人">{{ item.legalPersoName }}</el-descriptions-item>
            <el-descriptions-item label="电话">{{ item.legalPersonPhone }}</el-descriptions-item>
            <el-descriptions-item label="地址">{{ item.orgAddress }}</el-descriptions-item>
          </el-descriptions>
          </bm-info-window>
        </bm-marker> -->
        <template v-if="showName">
          <template v-if="currentIndex===1&&tableData.length">
            <bm-marker v-for="(item,index) in tableData" :key="index" :position="{lng: item.longitude, lat: item.latitude}" :icon="markerIcon" :dragging="false">
              <bm-label :title="item.fenceName" :content="item.fenceName" :label-style="{color: 'red', fontSize : '12px', textAlign: 'center' , width: '80px', background: 'none' , border: 'none'}" :offset="{width:-20, height: -20}" />
            </bm-marker>
          </template>
          <template v-if="currentIndex===2&&tableData1.length">
            <bm-marker v-for="(item,index) in tableData1" :key="index" :position="{lng: item.longitude, lat: item.latitude}" :icon="markerIcon" :dragging="false">
              <bm-label :title="item.fenceName" :content="item.fenceName" :label-style="{color: 'red', fontSize : '12px', textAlign: 'center' , width: '80px', background: 'none' , border: 'none'}" :offset="{width:-20, height: -20}" />
            </bm-marker>
          </template>
        </template>
        <bm-geolocation anchor="BMAP_ANCHOR_BOTTOM_RIGHT" :show-address-bar="true" :auto-location="true" />
      </baidu-map>
    </div>
  </div>
</template>

<script>
  import { selectOrgFence, saveOrgFence, selectUserFence, selectOrgFenceList } from '@/api'
  import { isPolygonsOverlap, isPolygonSelfIntersectant } from '@/utils/isPolygonsOverlap'
  import { setZoom } from '@/utils'
  const styleOptions = {
    strokeColor: '#4991E9', // 边线颜色。
    fillColor: '#4991E9', // 填充颜色。当参数为空时，圆形将没有填充效果。
    strokeWeight: 5, // 边线的宽度，以像素为单位。
    strokeOpacity: 0.8, // 边线透明度，取值范围0 - 1。
    fillOpacity: 0.6, // 填充的透明度，取值范围0 - 1。
    strokeStyle: 'dashed' // 边线的样式，solid或dashed。
  }
  export default {
    name: 'electronic-fence',
    components: {
      table1: require('./components/table1.vue').default,
      table2: require('./components/table2.vue').default
    },
    data() {
      return {
        showName: true,
        controlShow: false,
        markerIcon: { url: require('@/assets/images/makerIcon.png'), size: { width: 48, height: 48 }},
        drawBtn: true,
        editBtn: true,
        resetBtn: true,
        overlay: null, // 绘制的多边形
        polygons: [], // 原有多边形
        drawingManager: null, // 鼠标绘图工具
        flag: true,
        currentIndex: 1,
        currentBtnIndex: 0,
        currentTable: 'table1',
        currentItem: undefined,
        tableData: [], // 站点地图
        tableData2: [], // 站点列表
        tableData1: [], // 配送员
        chooseOrgId: null, // 配送员模式下选择的站点
        markerList: [], // 站点定位列表
        center: '',
        keyword: '',
        location: '',
        form: {
          markShow: false,
          position: {
            lng: '', lat: ''
          },
          id: null,
          orgId: null,
          orgName: '',
          orgSNNo: null,
          fenceName: '', // 围栏名称
          fenceType: null, // 围栏类型1：站点，2：配送员
          borderColor: '#4991E9', // 边界颜色
          fillColor: '#4991E9', // 填充颜色
          fillOpacity: 0.6, // 填充透明度
          coordinates: [], // 围栏范围
          fenceArea: '', // 围栏面积
          longitude: '', // 选点经度
          latitude: '' // 选点维度
        },
        rules: {
          fenceName: [{ required: true, message: '请输入围栏名称', trigger: 'blur' }],
          borderColor: [{ required: true, message: '请选择边界颜色', trigger: 'change' }],
          fillColor: [{ required: true, message: '请选择填充颜色', trigger: 'change' }],
          fillOpacity: [{ required: true, message: '请选择填充颜色透明度', trigger: 'change' }]
        },
        areaLabel: null // 围栏面积的地图对象
      }
    },
    watch: {
      flag: {
        handler(val) {
          if (val) {
            if (this.currentIndex === 1) {
              this.$refs.leftMainRef.style.cssText += ';width: 400px;'
              // this.$refs.rightMainRef.style.cssText += ';width: 80%;'
            } else {
              this.$refs.leftMainRef.style.cssText += ';width: 500px;'
            }
            this.$refs.tableRef.style.cssText += ';display: block;'
          } else {
            this.$refs.leftMainRef.style.cssText += ';width: 1%;'
            this.$refs.rightMainRef.style.cssText += ';width: 99%;'
            this.$refs.tableRef.style.cssText += ';display: none;'
          }
        }
      }
    },
    created() {
      const companyInfo = JSON.parse(sessionStorage.getItem('companyInfo'))
      // console.log('companyInfo', companyInfo )
      if (companyInfo) {
        this.center = companyInfo.city || '北京'
        this.location = companyInfo.city || '北京'
      }
    },
    mounted() {
      this.getData()
    },
    methods: {
      async getData() {
        if (this.tableData.length > 0) {
          await this.tableData.forEach(item => {
            this.map.removeOverlay(item.polygon)
          })
        }
        if (this.tableData1.length > 0) {
          await this.tableData1.forEach(item => {
            this.map.removeOverlay(item.polygon)
          })
        }
        const res = await selectOrgFence()
        const res1 = await selectOrgFenceList()
        this.tableData = []
        this.tableData2 = []
        this.tableData = res.data.map(item => {
          item.showDetail = false
          if (item.coordinates) {
            item.path = JSON.parse(item.coordinates)
            const options = {
              strokeColor: item.borderColor, // 边线颜色。
              fillColor: item.fillColor, // 填充颜色。当参数为空时，圆形将没有填充效果。
              strokeWeight: 5, // 边线的宽度，以像素为单位。
              strokeOpacity: 0.8, // 边线透明度，取值范围0 - 1。
              fillOpacity: item.fillOpacity || 0.6, // 填充的透明度，取值范围0 - 1。
              strokeStyle: 'dashed' // 边线的样式，solid或dashed。
            }
            const ps = []
            for (var i in item.path) {
              // eslint-disable-next-line no-undef
              ps.push(new BMap.Point(item.path[i].lng, item.path[i].lat))
            }
            // eslint-disable-next-line no-undef
            const polygon = new BMap.Polygon(ps, options) // 创建多边形
            item.polygon = polygon
            this.map.addOverlay(polygon)
          }
          return {
            position: {
              lng: item.lon, lat: item.lat
            },
            ...item
          }
        })
        this.tableData2 = res1.data.map(item => {
          return {
            position: {
              lng: item.lon, lat: item.lat
            },
            ...item
          }
        })
        // console.log(this.tableData)
        // console.log(this.tableData2)
        this.clearAll()
        setTimeout(() => {
          this.drawBtn = true
          this.flag = true
        })
      },
      // 判断绘制多边形是否相交，或自相交
      _checkPolygonsOverlap() {
        let rtn = false
        if (!this.overlay) {
          this.$alert('请绘制区域', '提示')
          return true
        }
        if (this.overlay.getPath().length === 2) {
          this.$alert('绘制区域不能为线条', '提示', {
            confirmButtonText: '确定',
            callback: action => {
              this.editing()
            }
          })
          return true
        }
        this.polygons.forEach(item => {
          if (isPolygonsOverlap(item.points, this.overlay.getPath())) {
            rtn = true
            this.$alert('绘制区域出现重叠,请重新编辑', '提示', {
              confirmButtonText: '确定',
              callback: action => {
                this.editing()
              }
            })
          }
        })
        if (isPolygonSelfIntersectant(this.overlay.getPath())) {
          rtn = true
          this.$alert('绘制区域出现自相交,请重新编辑', '提示', {
            confirmButtonText: '确定',
            callback: action => {
              this.editing()
            }
          })
        }
        return rtn
      },
      // 初始化绘制工具
      initDrawingManager() {
        // 实例化鼠标绘制工具
        // eslint-disable-next-line no-undef
        this.drawingManager = new BMapLib.DrawingManager(this.map, {
          isOpen: false, // 是否开启绘制模式
          enableDrawingTool: false, // 是否显示工具栏
          drawingToolOptions: {
            // eslint-disable-next-line no-undef
            anchor: BMAP_ANCHOR_TOP_RIGHT, // 位置
            // eslint-disable-next-line no-undef
            offset: new BMap.Size(5, 5), // 偏离值
            // eslint-disable-next-line no-undef
            drawingModes: [BMAP_DRAWING_POLYGON]
          },
          enableCalculate: false, // 计算面积
          circleOptions: styleOptions, // 圆的样式
          polylineOptions: styleOptions, // 线的样式
          polygonOptions: styleOptions, // 多边形的样式
          rectangleOptions: styleOptions // 矩形的样式
        })
        // 添加鼠标绘制工具监听事件，用于获取绘制结果
        this.drawingManager.addEventListener('overlaycomplete', e => {
          this.overlay = e.overlay
          // this.areaLabel = e.label
          console.log(e.calculate + '平方米')
          // if(e.calculate){
          //   this.form.fenceArea = e.calculate + '平方米'
          // }
          this._checkPolygonsOverlap()
        })
      },
      // 画选区
      draw() {
        if (this.form.borderColor && this.form.fillColor) {
          styleOptions.strokeColor = this.form.borderColor
          styleOptions.fillColor = this.form.fillColor
          styleOptions.fillOpacity = this.form.fillOpacity
        }
        this.initDrawingManager()
        this.drawingManager.open()
        this.drawingManager.setDrawingMode('polygon')
        this.drawBtn = true
        this.editBtn = false
        this.resetBtn = false
        this.flag = false
      },
      // 编辑
      editing() {
        if (!this.overlay) return
        if (!this.overlay) {
          this.drawingManager.close()
          this.editBtn = true
          this.resetBtn = true
          this.flag = false
        } else {
          // 编辑去掉选中效果
          this.overlay.setStrokeWeight(5)
          this.overlay.setStrokeStyle('dashed')
          this.overlay.setStrokeOpacity(0.8)
          const points = this.overlay.getPath()
          const isSeen = points.some(item => this.map.getBounds().containsPoint(item))
          if (!isSeen) setZoom(this.map, this.overlay.getPath())
          this.drawBtn = true
          this.resetBtn = false
          this.flag = false
          // console.log(this.overlay)
          this.overlay.enableEditing()
        }
      },
      // 重置
      clearAll() {
        if (!this.overlay) return
        this.map.removeOverlay(this.overlay)
        this.map.removeOverlay(this.areaLabel)
        this.areaLabel = null
        this.overlay = null
        this.form.fenceArea = null
        this.drawBtn = false
        this.editBtn = true
        this.resetBtn = true
      },
      // 取消
      async cancelView() {
        this.form = {
          id: 0,
          orgId: null,
          orgName: '',
          orgSNNo: null,
          fenceName: '', // 围栏名称
          fenceType: this.currentIndex, // 围栏类型1：站点，2：配送员
          borderColor: '', // 边界颜色
          fillColor: '', // 填充颜色
          coordinates: '', // 围栏范围
          fenceArea: '', // 围栏面积
          fillOpacity: 0.6,
          longitude: '',
          latitude: '',
          markShow: false
        }
        this.$refs.dataForm.clearValidate()
        // 在编辑中，取消编辑状态，删除已画围栏
        if (this.overlay) {
          await this.overlay.disableEditing()
          await this.map.removeOverlay(this.overlay)
          await this.map.removeOverlay(this.areaLabel)
        }
        // 在画区状态时，关闭画区状态
        if (this.drawingManager) {
          await this.drawingManager.close()
        }
        this.overlay = null
        this.areaLabel = null
        this.controlShow = false
        if (this.currentIndex === 1) {
          this.getData()
        } else {
          this.chooseOrg(this.chooseOrgId)
        }
      },
      // 完成
      async success() {
        if (this._checkPolygonsOverlap()) return
        let form = {}
        const arr = await this.overlay.getPath().map(item => {
          return {
            lng: item.lng,
            lat: item.lat
          }
        })
        // console.log('arr',arr)
        // console.log('path',this.currentItem.path)
        // return
        if (!arr.length) {
          this.$message.error('请添加电子围栏！')
          return
        }
        this.$refs.dataForm.validate(valid => {
          if (!valid) return
          form = {
            id: this.form.id,
            orgId: this.currentItem.orgId,
            orgName: this.currentItem.orgName,
            orgSNNo: this.currentItem.orgSNNo,
            fenceName: this.form.fenceName, // 围栏名称
            fenceType: this.currentIndex, // 围栏类型1：站点，2：配送员
            borderColor: this.form.borderColor, // 边界颜色
            fillColor: this.form.fillColor, // 填充颜色
            fillOpacity: this.form.fillOpacity, // 填充透明度
            coordinates: JSON.stringify(arr), // 围栏范围
            fenceArea: this.form.fenceArea, // 围栏面积
            isOpen: this.currentIndex === 2 && this.currentItem.isOpen ? 1 : 0,
            longitude: this.form.longitude, // 选点经度
            latitude: this.form.latitude // 选点维度
          }
          saveOrgFence(form).then(res => {
            this.$notify({
              title: '提示',
              message: '电子围栏保存成功',
              type: 'success',
              duration: 2000
            })
            this.controlShow = false
            this.form.markShow = false
            if (this.currentIndex === 1) {
              this.getData()
            } else {
              this.chooseOrg(this.chooseOrgId)
            }
          }).catch(err => {
            this.$message.error(err.message)
          })
        })
      },
      // 选中站点
      async chooseOrg(value) {
        this.chooseOrgId = value
        // 切换站点先清除上次站点的围栏
        this.controlShow = false
        if (this.tableData.length > 0) {
          await this.tableData.forEach(item => {
            this.map.removeOverlay(item.polygon)
          })
        }
        if (this.tableData1.length > 0) {
          await this.tableData1.forEach(item => {
            this.map.removeOverlay(item.polygon)
          })
        }
        // 查询新增显示的围栏
        await selectUserFence({ orgId: value }).then(res => {
          if (res.data) {
            this.tableData = []
            this.tableData1 = []
            this.tableData = res.data.filter(item => {
              if (item.fenceType === 1) {
                item.showDetail = false
                item.path = JSON.parse(item.coordinates)
                const options = {
                  strokeColor: item.borderColor, // 边线颜色。
                  fillColor: item.fillColor, // 填充颜色。当参数为空时，圆形将没有填充效果。
                  strokeWeight: 5, // 边线的宽度，以像素为单位。
                  strokeOpacity: 0.8, // 边线透明度，取值范围0 - 1。
                  fillOpacity: item.fillOpacity || 0.6, // 填充的透明度，取值范围0 - 1。
                  strokeStyle: 'dashed' // 边线的样式，solid或dashed。
                }
                const ps = []
                for (var i in item.path) {
                  // eslint-disable-next-line no-undef
                  ps.push(new BMap.Point(item.path[i].lng, item.path[i].lat))
                }
                // eslint-disable-next-line no-undef
                const polygon = new BMap.Polygon(ps, options) // 创建多边形
                item.polygon = polygon
                this.map.addOverlay(polygon)
                // eslint-disable-next-line no-undef
                this.map.centerAndZoom(new BMap.Point(item.lon, item.lat), 15)
                item.position = { lng: item.lon, lat: item.lat }
                return item
              }
            })
            this.tableData1 = res.data.filter(item => {
              if (item.fenceType === 2) {
                item.path = JSON.parse(item.coordinates)
                const options = {
                  strokeColor: item.borderColor, // 边线颜色。
                  fillColor: item.fillColor, // 填充颜色。当参数为空时，圆形将没有填充效果。
                  strokeWeight: 5, // 边线的宽度，以像素为单位。
                  strokeOpacity: 0.8, // 边线透明度，取值范围0 - 1。
                  fillOpacity: item.fillOpacity || 0.6, // 填充的透明度，取值范围0 - 1。
                  strokeStyle: 'dashed' // 边线的样式，solid或dashed。
                }
                const ps = []
                for (var i in item.path) {
                  // eslint-disable-next-line no-undef
                  ps.push(new BMap.Point(item.path[i].lng, item.path[i].lat))
                }
                // eslint-disable-next-line no-undef
                const polygon = new BMap.Polygon(ps, options) // 创建多边形
                item.polygon = polygon
                item.isOpen = item.isOpen === 1
                this.map.addOverlay(polygon)
                // eslint-disable-next-line no-undef
                this.map.centerAndZoom(new BMap.Point(item.lon, item.lat), 15)
                item.position = { lng: item.lon, lat: item.lat }
                return item
              }
            })
            // console.log(this.tableData)
            // console.log(this.tableData1)
            this.clearAll()
            setTimeout(() => {
              this.drawBtn = true
              this.flag = true
            }, 1000)
          }
        }).catch(err => {
          console.log(err)
          this.tableData = []
          this.tableData1 = []
        })
        // console.log(res.data)
      },
      // 显示信息弹框
      async showInfo(item) {
        // console.log(item.showDetail)
        // console.log(this.tableData)
        await this.tableData.forEach(i => {
          i.showDetail = false
        })
        item.showDetail = true
      },
      // 选中子围栏
      currentChild(row) {
        this.chooseOrgId = row.orgId
        this.changeCurrent(2)
        console.log(row)
      },
      // 选中行
      currentRow(row) {
        console.log(this.$btnPermission([50301, 4]))
        if (!this.$btnPermission([50301, 4])) {
          return
        }
        console.log('row', row)
        // 切换站点时关掉上次编辑
        if (this.overlay) {
          this.overlay.disableEditing()
          // 去掉上次选中效果
          this.overlay.setStrokeWeight(5)
          this.overlay.setStrokeStyle('dashed')
          this.overlay.setStrokeOpacity(0.8)
        }
        if (!row) return
        this.overlay = null
        if (this.currentIndex === 1) {
          this.tableData.forEach(item => {
            if (row.orgId === item.orgId) {
              row.polygon = item.polygon
              row.path = item.path
            }
          })
        }
        this.form = {
          id: 0,
          orgId: row.orgId,
          orgName: row.orgName,
          orgSNNo: row.orgSNNo,
          fenceName: '', // 围栏名称
          fenceType: this.currentIndex, // 围栏类型1：站点，2：配送员
          borderColor: '', // 边界颜色
          fillColor: '', // 填充颜色
          coordinates: '', // 围栏范围
          fenceArea: '', // 围栏面积
          fillOpacity: 0.6,
          longitude: '',
          latitude: '',
          markShow: false
        }
        if (row.id) {
          this.form = { ...row }
          this.form.longitude = row.longitude ? row.longitude : row.lon
          this.form.latitude = row.latitude ? row.latitude : row.lat
        }
        if (this.$btnPermission([50301, 3])) {
          this.controlShow = true
        }
        this.drawBtn = false
        this.currentItem = row
        this.clearAll()
        // eslint-disable-next-line no-undef
        this.map.centerAndZoom(new BMap.Point(row.lon, row.lat), 15)
        if (!row || !row.isFence) return
        // 如果有围栏坐标，则显示在地图上,arr为后端返回的坐标数组，要按顺序来
        // const arr = JSON.parse(row.coordinates)
        // const options = {
        //   strokeColor: row.borderColor, // 边线颜色。
        //   fillColor: row.fillColor, // 填充颜色。当参数为空时，圆形将没有填充效果。
        //   strokeWeight: 5, // 边线的宽度，以像素为单位。
        //   strokeOpacity: 0.8, // 边线透明度，取值范围0 - 1。
        //   fillOpacity: 0.6, // 填充的透明度，取值范围0 - 1。
        //   strokeStyle: 'dashed' // 边线的样式，solid或dashed。
        // }
        // const polygon = new BMap.Polygon(arr, options) // 创建多边形
        // this.map.addOverlay(polygon)
        this.overlay = row.polygon
        setZoom(this.map, this.overlay.getPath())
        this.drawBtn = true
        this.editBtn = false
        this.resetBtn = false
        // 新增选中围栏效果
        this.chooseFence()
      },
      // 更换模式
      async changeCurrent(val) {
        // 切换删除全部围栏
        this.controlShow = false
        await this.tableData.forEach(item => {
          this.map.removeOverlay(item.polygon)
        })
        await this.tableData1.forEach(item => {
          this.map.removeOverlay(item.polygon)
        })
        this.overlay = null
        this.currentIndex = val
        this.currentTable = 'table' + val
        this.tableData = []
        this.clearAll()
        if (val === 1) {
          this.getData()
        } else {
          this.tableData1 = []
          if (this.chooseOrgId) {
            this.chooseOrg(this.chooseOrgId)
          }
        }
      },
      // 配送员模式新增
      add(info) {
        if (this.tableData.length === 0 &&
          this.tableData1.length === 0) {
          this.$message.error('站点围栏不存在，请您先新增站点围栏')
          return
        }
        console.log('info', info)
        this.form = {
          id: 0,
          orgId: info.orgId,
          orgName: info.orgName,
          orgSNNo: info.orgSNNo,
          fenceName: '', // 围栏名称
          fenceType: this.currentIndex, // 围栏类型1：站点，2：配送员
          borderColor: '', // 边界颜色
          fillColor: '', // 填充颜色
          coordinates: '', // 围栏范围
          fenceArea: '', // 围栏面积
          fillOpacity: 0.6,
          longitude: '',
          latitude: '',
          markShow: false
        }
        this.currentItem = info
        this.controlShow = true
        this.drawBtn = false
        setTimeout(() => {
          this.$refs.dataForm.clearValidate()
        }, 100)
      },
      // 更改边框颜色
      changeBorderColor(value) {
        // console.log(value)
        if (this.overlay) {
          this.overlay.setStrokeColor(value)
        }
      },
      // 更改填充颜色
      changeFillColor(value) {
        // console.log(value)
        if (this.overlay) {
          this.overlay.setFillColor(value)
        }
      },
      // 更改填充颜色透明度
      changeFillOpacity(value) {
        // console.log(value)
        if (this.overlay) {
          this.overlay.setFillOpacity(value)
        }
      },
      // 选中围栏
      chooseFence() {
        if (this.overlay) {
          this.overlay.setStrokeWeight(10)
          this.overlay.setStrokeStyle('solid')
          this.overlay.setStrokeOpacity(1)
        }
      },
      // 地图选点
      chooseMark() {
        if (!this.form.longitude || !this.form.latitude) {
          this.form.longitude = this.currentItem.lon
          this.form.latitude = this.currentItem.lat
        }
        this.form.markShow = !this.form.markShow
        this.form = { ...this.form }
      },
      // 拖拽选点
      dragend(event) {
        // console.log('event',event)
        this.form.longitude = event.point.lng.toFixed(6)
        this.form.latitude = event.point.lat.toFixed(6)
        this.form = { ...this.form }
        // console.log('longitude',this.form.longitude)
        // console.log('latitude',this.form.latitude)
      },
      // 地图初始化
      ready({ BMap, map }) {
        this.BMap = BMap
        this.map = map
      },
      changeView(flag) {
        this.flag = flag
      }
    }
  }
</script>

<style lang="scss" scoped>
.search-box {
  padding: 12px;
}
.toolbar {
  position: absolute;
  top: 5px;
  right: 5px;
  width: 275px;
  padding: 12px;
  background: #FFF;
  border-radius: 4px;
  box-shadow: 0 4px 12px 0 rgba(0, 0, 0, 0.2);
  .title {
    padding-bottom: 5px;
    margin-bottom: 10px;
    border-bottom: 1px solid #d9d9d9;
  }
  .toolbar-item {
    margin-bottom: 6px;
    .el-button + .el-button {
      margin-left: 0;
    }
  }
  .toolbar-item:last-child {
    margin-bottom: 0;
  }
  .form {
    /deep/ .box {
      left: -37px;
      z-index: 1002;
    }
  }
}
.edit-view {
  width: 6vw;
  height: 25vh;
  padding: 20px 20px 0 0;
  .edit-container {
    display: flex;
    align-items: center;
    width: 100%;
    height: 100%;
    padding: 14px;
    background: #fff;
    box-shadow: 0 4px 4px 0 rgba(94, 94, 94, 0.25);
    flex-direction: column;
    .edit-item {
      display: flex;
      align-items: center;
      justify-content: center;
      width: 4vw;
      margin-bottom: 7px;
      font-size: 14px;
      color: #131414;
      cursor: pointer;
      border: 1px solid #d9d9d9;
      border-radius: 3px;
      flex: 1;
    }
  }
}
.currentTable {
  color: $themeColor !important;
  border-bottom: 2px solid $themeColor;
}
.container {
  display: flex;
  height: 100%;
  background-color: #fff;
  .bm-view {
    width: 100%;
    height: 100%;
  }
  .left-main {
    display: flex;
    width: 400px;
    height: 100%;
    border: 1px solid #ebeff5;
    border-radius: 2px;
    box-shadow: 0 4px 4px 0 rgba(94, 94, 94, 0.25);
    transition: width 0.3s;
    .table {
      width: 95%;
      height: 100%;
      transition: width 0.3s;
      .table-container {
        width: 100%;
        height: calc(100% - 40px);
      }
      .title-container {
        display: flex;
        width: 100%;
        height: 30px;
        margin-bottom: 5px;
        transition: width 0.3s;
        .title-name {
          font-size: 14px;
          line-height: 30px;
          color: #131414;
          text-align: center;
          cursor: pointer;
          flex: 1;
        }
        // .title-name:nth-child(2) {
        //   cursor: not-allowed;
        // }
      }
    }
    .toggleBtn {
      display: flex;
      align-items: center;
      flex: 1;
      height: 100%;
      i {
        cursor: pointer;
      }
    }
  }
  .right-main {
    position: relative;
    height: 100%;
    transition: width 0.3s;
    flex: 1;
    .name-box {
      position: absolute;
      top: 20px;
      left: 225px;
      z-index: 1200;
    }
  }
}

/* 隐藏百度图片Logo */
/deep/ .BMap_cpyCtrl {
  display: none;
}
/deep/ .anchorBL {
  display: none;
}
</style>
